package com.xmhmyh.generalframework.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: 于丁
 * @DateTime: 2021/1/27 4:00 下午
 */
public class PhoneLocation {
    public static JSONArray queryPhone(String phone){
        String url="http://api.ip138.com/mobile/?mobile="+phone;
        String token="00385e44cc4672644804d490021f4e24";
        String s = getGsd(url,token);
        JSONArray slist = new JSONArray();
        if(StringUtils.isNotEmpty(s)){
            JSONObject json = JSONObject.parseObject(s);
            slist =  (JSONArray) json.get("data");
        }
        return slist;
    }
    public static String getGsd(String urlString,String token) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(5 * 1000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("token",token);
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                StringBuilder builder = new StringBuilder();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(),"utf-8"));
                for (String s = br.readLine(); s != null; s = br
                        .readLine()) {
                    builder.append(s);
                }
                br.close();
                return builder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
